import React, { useState } from 'react';
import { dbTester } from '../utils/dbTester';
import { dbManager, ChatRecord, LigHistoryRecord } from '../utils/indexedDB';

const TestPage: React.FC = () => {
    const [testResults, setTestResults] = useState<string[]>([]);
    const [isRunning, setIsRunning] = useState(false);
    const [allChats, setAllChats] = useState<ChatRecord[]>([]);
    const [allLigHistory, setAllLigHistory] = useState<LigHistoryRecord[]>([]);
    const [activeTab, setActiveTab] = useState<'chat' | 'ligHistory'>('chat');

    // 运行测试
    const runTests = async () => {
        setIsRunning(true);
        setTestResults([]);

        // 重定向console.log输出到状态
        const originalLog = console.log;
        const originalError = console.error;
        const originalAssert = console.assert;

        console.log = (...args) => {
            originalLog(...args);
            setTestResults(prev => [...prev, args.join(' ')]);
        };

        console.error = (...args) => {
            originalError(...args);
            setTestResults(prev => [...prev, `错误: ${args.join(' ')}`]);
        };

        console.assert = (condition, ...args) => {
            if (!condition) {
                originalAssert(condition, ...args);
                setTestResults(prev => [...prev, `断言失败: ${args.join(' ')}`]);
            }
        };

        try {
            await dbTester.runTests();
            await loadAllData(); // 刷新数据
        } finally {
            // 恢复原始控制台方法
            console.log = originalLog;
            console.error = originalError;
            console.assert = originalAssert;
            setIsRunning(false);
        }
    };

    // 加载所有数据
    const loadAllData = async () => {
        await dbManager.initDB();
        const chats = await dbManager.getAllChats();
        const ligHistory = await dbManager.getAllLigHistory();
        setAllChats(chats);
        setAllLigHistory(ligHistory);
    };

    // 创建测试聊天
    const createTestChat = async () => {
        await dbManager.initDB();
        const newChat: ChatRecord = {
            chatId: `manual-test-${Date.now()}`,
            messages: [
                {
                    role: 'user',
                    content: '你好，这是一条测试消息',
                    timestamp: Date.now()
                },
                {
                    role: 'assistant',
                    content: '你好，我是AI助手',
                    timestamp: Date.now() + 1000
                }
            ],
            model: 'deepseek-r1',
            title: '手动测试聊天',
            desc: '这是一个手动创建的测试聊天'
        };

        await dbManager.addChat(newChat);
        await loadAllData();
    };

    // 创建测试LigHistory记录
    const createTestLigHistory = async () => {
        await dbManager.initDB();
        const newRecord: LigHistoryRecord = {
            id: Date.now(),
            name: `测试记录 ${new Date().toLocaleString()}`
        };

        await dbManager.addLigHistory(newRecord);
        await loadAllData();
    };

    // 清空聊天记录
    const clearChats = async () => {
        const confirmClear = window.confirm('确定要清空所有聊天记录吗？此操作不可撤销！');
        if (!confirmClear) return;

        await dbManager.initDB();

        // 删除所有聊天记录
        for (const chat of allChats) {
            await dbManager.deleteChat(chat.chatId);
        }

        await loadAllData();
    };

    // 清空LigHistory记录
    const clearLigHistory = async () => {
        const confirmClear = window.confirm('确定要清空所有LigHistory记录吗？此操作不可撤销！');
        if (!confirmClear) return;

        await dbManager.initDB();
        await dbManager.clearAllLigHistory();
        await loadAllData();
    };

    return (
        <div style={{ padding: '20px', maxWidth: '1000px', margin: '0 auto' }}>
            <h1>IndexedDB 测试页面</h1>

            <div style={{ marginBottom: '20px' }}>
                <button
                    onClick={runTests}
                    disabled={isRunning}
                    style={{ padding: '10px 20px', marginRight: '10px' }}
                >
                    {isRunning ? '测试运行中...' : '运行自动测试'}
                </button>

                <button
                    onClick={loadAllData}
                    style={{ padding: '10px 20px', marginRight: '10px' }}
                >
                    刷新数据
                </button>

                <button
                    onClick={activeTab === 'chat' ? createTestChat : createTestLigHistory}
                    style={{ padding: '10px 20px', marginRight: '10px' }}
                >
                    {activeTab === 'chat' ? '创建测试聊天' : '创建测试LigHistory'}
                </button>

                <button
                    onClick={activeTab === 'chat' ? clearChats : clearLigHistory}
                    style={{ padding: '10px 20px', backgroundColor: '#ff4d4f', color: 'white', border: 'none' }}
                >
                    {activeTab === 'chat' ? '清空聊天记录' : '清空LigHistory记录'}
                </button>
            </div>

            <div style={{ display: 'flex', gap: '20px' }}>
                {/* 测试结果 */}
                <div style={{ flex: 1 }}>
                    <h2>测试结果</h2>
                    <div
                        style={{
                            border: '1px solid #ccc',
                            padding: '10px',
                            borderRadius: '5px',
                            height: '400px',
                            overflow: 'auto',
                            backgroundColor: '#f5f5f5',
                            fontFamily: 'monospace',
                            whiteSpace: 'pre-wrap'
                        }}
                    >
                        {testResults.length === 0 ? (
                            <div style={{ color: '#888', textAlign: 'center', marginTop: '20px' }}>
                                运行测试后结果将显示在这里
                            </div>
                        ) : (
                            testResults.map((result, index) => (
                                <div
                                    key={index}
                                    style={{
                                        padding: '5px 0',
                                        borderBottom: '1px solid #eee',
                                        color: result.includes('成功') ? 'green' :
                                            result.includes('错误') || result.includes('失败') ? 'red' : 'black'
                                    }}
                                >
                                    {result}
                                </div>
                            ))
                        )}
                    </div>
                </div>

                {/* 数据预览 */}
                <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', marginBottom: '10px' }}>
                        <button
                            onClick={() => setActiveTab('chat')}
                            style={{
                                flex: 1,
                                padding: '8px',
                                backgroundColor: activeTab === 'chat' ? '#1890ff' : '#f0f0f0',
                                color: activeTab === 'chat' ? 'white' : 'black',
                                border: 'none',
                                borderRadius: '4px 0 0 4px'
                            }}
                        >
                            聊天记录 ({allChats.length})
                        </button>
                        <button
                            onClick={() => setActiveTab('ligHistory')}
                            style={{
                                flex: 1,
                                padding: '8px',
                                backgroundColor: activeTab === 'ligHistory' ? '#1890ff' : '#f0f0f0',
                                color: activeTab === 'ligHistory' ? 'white' : 'black',
                                border: 'none',
                                borderRadius: '0 4px 4px 0'
                            }}
                        >
                            LigHistory ({allLigHistory.length})
                        </button>
                    </div>

                    {activeTab === 'chat' ? (
                        <div
                            style={{
                                border: '1px solid #ccc',
                                padding: '10px',
                                borderRadius: '5px',
                                height: '400px',
                                overflow: 'auto'
                            }}
                        >
                            {allChats.length === 0 ? (
                                <div style={{ color: '#888', textAlign: 'center', marginTop: '20px' }}>
                                    数据库中没有聊天记录
                                </div>
                            ) : (
                                allChats.map(chat => (
                                    <div
                                        key={chat.chatId}
                                        style={{
                                            padding: '10px',
                                            marginBottom: '10px',
                                            border: '1px solid #eee',
                                            borderRadius: '5px'
                                        }}
                                    >
                                        <h3>{chat.title || chat.chatId}</h3>
                                        <div><strong>ID:</strong> {chat.chatId}</div>
                                        <div><strong>模型:</strong> {chat.model}</div>
                                        <div><strong>描述:</strong> {chat.desc || '无'}</div>
                                        <div><strong>消息数:</strong> {chat.messages.length}</div>

                                        {chat.messages.length > 0 && (
                                            <div style={{ marginTop: '10px' }}>
                                                <h4>消息:</h4>
                                                {chat.messages.slice(0, 3).map((msg, index) => (
                                                    <div
                                                        key={index}
                                                        style={{
                                                            padding: '5px',
                                                            margin: '5px 0',
                                                            backgroundColor: msg.role === 'user' ? '#e1f5fe' : '#f1f8e9',
                                                            borderRadius: '5px'
                                                        }}
                                                    >
                                                        <div><strong>{msg.role}</strong> ({new Date(msg.timestamp).toLocaleString()})</div>
                                                        <div>{msg.content}</div>
                                                    </div>
                                                ))}
                                                {chat.messages.length > 3 && (
                                                    <div style={{ color: '#888', textAlign: 'center' }}>
                                                        ...还有 {chat.messages.length - 3} 条消息
                                                    </div>
                                                )}
                                            </div>
                                        )}

                                        <button
                                            onClick={async () => {
                                                await dbManager.deleteChat(chat.chatId);
                                                await loadAllData();
                                            }}
                                            style={{
                                                marginTop: '10px',
                                                padding: '5px 10px',
                                                backgroundColor: '#ff4d4f',
                                                color: 'white',
                                                border: 'none',
                                                borderRadius: '3px'
                                            }}
                                        >
                                            删除
                                        </button>
                                    </div>
                                ))
                            )}
                        </div>
                    ) : (
                        <div
                            style={{
                                border: '1px solid #ccc',
                                padding: '10px',
                                borderRadius: '5px',
                                height: '400px',
                                overflow: 'auto'
                            }}
                        >
                            {allLigHistory.length === 0 ? (
                                <div style={{ color: '#888', textAlign: 'center', marginTop: '20px' }}>
                                    数据库中没有LigHistory记录
                                </div>
                            ) : (
                                <>
                                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                        <thead>
                                            <tr style={{ backgroundColor: '#f0f0f0' }}>
                                                <th style={{ padding: '8px', textAlign: 'left', border: '1px solid #ddd' }}>ID</th>
                                                <th style={{ padding: '8px', textAlign: 'left', border: '1px solid #ddd' }}>名称</th>
                                                <th style={{ padding: '8px', textAlign: 'center', border: '1px solid #ddd' }}>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {allLigHistory.map(record => (
                                                <tr key={record.id} style={{ borderBottom: '1px solid #eee' }}>
                                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>{record.id}</td>
                                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>{record.name}</td>
                                                    <td style={{ padding: '8px', textAlign: 'center', border: '1px solid #ddd' }}>
                                                        <button
                                                            onClick={async () => {
                                                                await dbManager.deleteLigHistory(record.id);
                                                                await loadAllData();
                                                            }}
                                                            style={{
                                                                padding: '3px 8px',
                                                                backgroundColor: '#ff4d4f',
                                                                color: 'white',
                                                                border: 'none',
                                                                borderRadius: '3px'
                                                            }}
                                                        >
                                                            删除
                                                        </button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default TestPage; 